package nix.bs.dao;

import java.sql.SQLException;

import nix.bs.domain.User;
import nix.jdbc.TxQueryRunner;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

public class UserDao {

	private QueryRunner qr = new TxQueryRunner();

	/**
	 * 按用户名查询
	 */
	public User findByUsername(String username) {
		try {
			return qr.query("select * from tb_user where username = ?",
					new BeanHandler<User>(User.class), username);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 按Email查询
	 */
	public User findByEmail(String email) {
		try {
			return qr.query("select * from tb_user where email = ?",
					new BeanHandler<User>(User.class), email);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 插入User
	 */
	public void add(User user) {
		try {
			qr.update(
					"insert into tb_user (uid, username, password, email, code, state) values (?, ?, ?, ?, ?, ?)",
					user.getUid(), user.getUsername(), user.getPassword(),
					user.getEmail(), user.getCode(), user.isState());
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 按Code查询
	 */
	public User findByCode(String code) {
		try {
			return qr.query("select * from tb_user where code = ?",
					new BeanHandler<User>(User.class), code);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 修改状态
	 */
	public void updateState(String uid, boolean state) {
		try {
			qr.update("update tb_user set state = ? where uid = ?", state, uid);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
}
